package org.sss.interestrates;

public class MakeFraction {
	private static final String FRACTION_SEPARATOR_32 = "-";
	public StringBuffer makeFraction(double value) {
		boolean isNegative = false;
		if (value < -0.00001) {
			isNegative = true;
			value = value * (-1);
		}
		int mant = (int) value;
		double remain = value - mant;
		int fraction = (int) (remain * 32); // Calculate the "ticks" -- i.e. the third digit after the hyphen
		double correction = remain -((double) fraction) / 32; 
		int ticks = (int) Math.round(correction * 256); //
				// The maximum valid value of the ticks is 7. 
				// Due to the rounding above, it may have been calculated as 8. If it is eight,
				// then increment the fraction -- i.e. the first two digits after
				// the hyphen and don't append a third digit. 
		String ticksString = ""; 
		if(ticks >= 8){ 
			fraction++; ticksString = "0"; 
		} else	if(ticks == 4) { // When the ticks equals 4, the third "digit" is set to a plus sign.
			ticksString = "+"; 
		} else { // Simply convert the ticks digit to a string. 
			ticksString = ticks + ""; 
		} // end if ticks = 8 
		// If the fraction was increased to 32 (probably by the ticks >= 8
		// adjustment), then roll the fraction over to 0 and increase the whole number part.
											
		 if(fraction == 32) { 
			 fraction = 0; 
			 mant++; 
		 } 
		 String fractionString = fraction + "";
		// Ensure that the fraction string is at least two digits.
		 if(fraction <= 9) 
			 fractionString = "0" + fractionString;
		 
		 StringBuffer result = new StringBuffer(); 
		 if(isNegative) 
			result.append("-");
		result.append(mant);
		result.append(FRACTION_SEPARATOR_32);
		result.append(fractionString);
		result.append(ticksString);
		return result; 
	}
}